import os
import re
import threading

import requests
from lxml import etree

# from NetworkModule import NetworkModule


class NovelModule:

    def __init__(self):
        """
        小说模块
        """

        self.CachePath = "C:/RoxyCache/"
        self.step = "none"
        self.network_running = False
        self.now_book = None
        self.now_chapter = None
        self.chapters = []
        self.now_content = []
        self.headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            "Content-Length": 52,
            "Content-Type": "application/x-www-form-urlencoded",
            "Host": "m.06qb.com",
            "Origin": "http://m.06qb.com",
            "Referer": "http://m.06qb.com/",
            "Upgrade-Insecure-Requests": 1,
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
        }

    def search_novel(self, key):
        """
        搜索小说
        :param key:
        :return:
        """

        self.step = "search_book"
        data = {"action": "search"}
        data["q"] = key
        r = requests.post(url="http://m.06qb.com/home/search", headers=self.headers, data=data)
        tree = etree.HTML(r.text)
        reslist = []
        try:
            for i in range(1, 20):
                res = tree.xpath(f"/html/body/div[5]/dl[{i}]/dd/h3/a")
                reslist.append({"name": res[0].text, "url": "http://m.06qb.com" + res[0].attrib['href']})
        except IndexError:
            print("Novel Searching Error [Index Error]")
        return reslist

    def get_content(self, url):
        """
        获取内容
        :param url:
        :return:
        """

        r = requests.get(url=url)
        tree = etree.HTML(r.text)
        fa = tree.xpath("//*[@id=\"content\"]")[0]
        res = fa.xpath('string(.)')

        temp = res.split("\xa0\xa0\xa0\xa0")
        res = []
        for i in temp:
            temp2 = i.split("\n")
            for j in temp2:
                res.append(j)

        return res

    def set_content(self, num):
        """
        设置内容
        :param num:
        :return:
        """

        self.step = "ready_to_read"
        self.now_chapter = num
        self.now_content = self.get_content(self.chapters[num]['url'])

    def get_chapter(self, url):
        """
        获取章节
        :param url:
        :return:
        """

        self.step = "get_chapter"
        r = requests.get(url=url).text
        r = r.split("<div class=\"mulu\">")[2]
        pattern = r"<a href=\".*?\" target=\"_blank\" title=\".*?\">.*?</a>"
        res = re.findall(pattern=pattern, string=r)
        self.chapters = []
        for i in res:
            url = "http://m.06qb.com" + i.split("<a href=\"")[1].split("\" target=\"_blank\" title=\"")[0]
            name = i.split("target=\"_blank\" title=\"")[1].split("\">")[0]
            self.chapters.append({"url": url, "name": name})
        return self.chapters

    def run_cherrypy(self):
        """
        启动Cherrypy
        :return:
        """

        self.network_running = True
        temp = self.now_content
        self.now_content = []
        for i in temp:
            if i == "铅笔小说":
                continue
            self.now_content.append(i)

        self.network = NetworkModule(self.chapters[self.now_chapter]["name"], self.now_content)
        # self.network.set_route()
        with open (self.CachePath + "Network/network.roxycache", "w") as f:
            f.write("http://localhost:8009/read/")
        thr_run_bottle = threading.Thread(target=self.network.run_network)
        thr_run_bottle.start()
        os.popen("DLL\\RoxyEbookReader.exe")


if __name__ == "__main__":
    novel = NovelModule()
    # reslist = novel.search_novel()
    # print(reslist)
    # novel.get_content(reslist[0]["url"])
    novel.get_charactors("http://m.06qb.com/lightnovel/books/85778/")
